class Deque {
  constructor () {
    this._tail = 0 // 指向队尾的下一个位置
    this._front = 0
    this._items = {}
  }

  isEmpty () {
    return this.getSize() === 0
  }

  getSize () {
    return this._tail - this._front
  }

  addFront (element) {
    // 头部添加分几种情况
    // 队列为空
    if (this.isEmpty()) {
      this.addBack(element)
    } else if (this._front > 0) {
      // 队头索引>0
      this._front--
      this._items[this._front] = element
    } else {
      // 队头索引=0，队列不为空, 先后移元素
      for (let i = this._tail; i > this._front; i--) {
        this._items[i] = this._items[i - 1]
      }
      this._tail++
      this._items[this._front] = element
    }
  }

  addBack (element) {
    this._items[this._tail] = element
    this._tail++
  }

  removeFront () {
    if (this.isEmpty()) {
      throw new Error('queue is empty')
    }
    const result = this._items[this._front]
    delete this._items[this._front]
    this._front++
    return result
  }

  removeBack () {
    if (this.isEmpty()) {
      throw new Error('queue is empty')
    }
    this._tail--
    const result = this._items[this._tail]
    delete this._items[this._tail]
    return result
  }

  peekBack () {
    return this.isEmpty() ? undefined : this._items[this._tail - 1]
  }

  peekFront () {
    return this.isEmpty() ? undefined : this._items[this._front]
  }
}

export default Deque
